const express = require('express');
const router = express.Router();
const pool = require('../config/db');
const ProjectMember = require('../models/ProjectMember');
const { logOperation } = require('./logs');

// 状态码定义
const CODE = {
  SUCCESS: 0,
  PARAM_ERROR: 1001,
  NOT_FOUND: 1002,
  SERVER_ERROR: 500,
  NO_PERMISSION: 1003
};

// 获取项目成员列表
router.get('/list/:projectId', async (req, res) => {
  try {
    const { projectId } = req.params;
    const members = await ProjectMember.getProjectMembers(projectId);

    res.json({
      code: CODE.SUCCESS,
      message: '获取项目成员成功',
      data: members
    });
  } catch (error) {
    console.error('获取项目成员错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

// 添加项目成员
router.post('/add', async (req, res) => {
  try {
    const { 
      projectId, 
      userId, 
      role = 'member' 
    } = req.body;

    // 检查是否已经是成员
    const isMember = await ProjectMember.isMember(projectId, userId);
    if (isMember) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '用户已是项目成员'
      });
    }

    const memberId = await ProjectMember.addMember(projectId, userId, role);

    // 记录操作日志
    await logOperation(
      // req.user.userId,
      // 'create',
      // '项目成员管理',
      // `添加项目成员：项目${projectId}，用户${userId}`,
      // req.ip,
      // req.headers['user-agent']
      {
        userId: req.user.userId,
        type: 'create',
        module: '项目成员管理',
        details: `添加项目成员：项目${projectId}，用户${userId}`,
        ipAddress: req.ip,
        userAgent: req.headers['user-agent']
      }
    );

    res.json({
      code: CODE.SUCCESS,
      message: '添加项目成员成功',
      data: { memberId }
    });
  } catch (error) {
    console.error('添加项目成员错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

// 更新项目成员角色
router.post('/update-role', async (req, res) => {
  try {
    const { 
      projectId, 
      userId, 
      newRole 
    } = req.body;

    // 参数校验
    if (!projectId || !userId || !newRole) {
      return res.status(400).json({ 
        error: '缺少必要参数', 
        details: {
          projectId: projectId ? '✓' : '✗',
          userId: userId ? '✓' : '✗', 
          newRole: newRole ? '✓' : '✗'
        }
      });
    }

    // 检查角色是否合法
    const validRoles = ['owner', 'admin', 'member', 'viewer'];
    if (!validRoles.includes(newRole)) {
      return res.status(400).json({ 
        error: '无效的角色', 
        validRoles: validRoles 
      });
    }

    const success = await ProjectMember.updateMemberRole(projectId, userId, newRole);

    if (!success) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: '项目成员不存在'
      });
    }

    // 记录操作日志
    await logOperation(
      // req.user.userId,
      // 'update',
      // '项目成员管理',
      // `更新项目成员角色：项目${projectId}，用户${userId}，新角色${newRole}`,
      // req.ip,
      // req.headers['user-agent']
      {
        userId: req.user.userId,
        type: 'update',
        module: '项目成员管理',
        details: `更新项目成员角色：项目${projectId}，用户${userId}，新角色${newRole}`,
        ipAddress: req.ip,
        userAgent: req.headers['user-agent']
      }
    );

    res.json({
      code: CODE.SUCCESS,
      message: '更新项目成员角色成功'
    });
  } catch (error) {
    console.error('更新项目成员角色错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

// 移除项目成员
router.delete('/remove', async (req, res) => {
  try {
    const { memberId, projectId,userId} = req.query;

    const success = await ProjectMember.removeMember(memberId)
 
    if (!success) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: '项目成员不存在'
      });
    }

    // 记录操作日志
    await logOperation(
     {
       userId: req.user.userId,
       type: 'delete',
       module: '项目成员管理',
       details: `移除项目成员：项目${projectId}，用户${userId}`,
       ipAddress: req.ip,
       userAgent: req.headers['user-agent']
     }
    );

    res.json({
      code: CODE.SUCCESS,
      message: '移除项目成员成功'
    });
  } catch (error) {
    console.error('移除项目成员错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

module.exports = router;
